package com.cheer.ba.view.activity;

import android.Manifest;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.model.NaviPara;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.navi.BaiduMapAppNotSupportNaviException;
import com.baidu.mapapi.navi.BaiduMapNavigation;
import com.baidu.mapapi.navi.NaviParaOption;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.route.BikingRouteResult;
import com.baidu.mapapi.search.route.DrivingRouteLine;
import com.baidu.mapapi.search.route.DrivingRoutePlanOption;
import com.baidu.mapapi.search.route.DrivingRouteResult;
import com.baidu.mapapi.search.route.IndoorRouteResult;
import com.baidu.mapapi.search.route.MassTransitRouteResult;
import com.baidu.mapapi.search.route.OnGetRoutePlanResultListener;
import com.baidu.mapapi.search.route.PlanNode;
import com.baidu.mapapi.search.route.RoutePlanSearch;
import com.baidu.mapapi.search.route.TransitRouteResult;
import com.baidu.mapapi.search.route.WalkingRouteResult;
import com.baidu.mapapi.utils.OpenClientUtil;
import com.cheer.ba.R;
import com.cheer.ba.constant.IntentKey;
import com.cheer.ba.utils.StringUtils;
import com.cheer.ba.utils.ToastUtil;
import com.cheer.ba.utils.baidu.DrivingRouteOverlay;
import com.cheer.ba.view.base.BaseCommAty;
import com.cheer.ba.view.dialog.DialogUtils;

/**
 * 路线规划导航
 *
 * @author HQ
 *         created at 2017/5/17 0017 14:27
 */
public class NaviMapAty extends BaseCommAty implements BaiduMap.OnMapLoadedCallback, OnGetRoutePlanResultListener {

    //地图控件
    private MapView mMapView;
    private BaiduMap mBaiduMap;
    //导航加油站名称
    private TextView mTxtNaviOilName;
    //导航加油站地址
    private TextView mTxtNaviOilAddress;

    // 路线搜索相关,也可去掉地图模块独立使用
    private RoutePlanSearch mRouteSearch = null;

    //当前位置纬度
    private double mCurrentLat = 0.0;
    //当前位置经度
    private double mCurrentLon = 0.0;
    //终点纬度
    private double mEndLat = 0.0;
    //终点经度
    private double mEndLon = 0.0;
    //终点地址
    private String mEndAddress;
    //油站名称
    private String mOilName;

    private static final String[] authBaseArr = {Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.ACCESS_FINE_LOCATION};
    private static final String[] authComArr = {Manifest.permission.READ_PHONE_STATE};


    @Override
    protected boolean isSupportSwipeback() {
        return false;
    }


    @Override
    public View loadView(LayoutInflater inflater, View childView) {
        return super.loadView(inflater, inflater.inflate(R.layout.aty_navi_map, null, false));
    }

    @Override
    public void initView() {
        setTitleText(getString(R.string.oil_navigation));
        init();
        mCurrentLat = getIntent().getDoubleExtra(IntentKey.Location.KEY_START_LATITUDE, 0);
        mCurrentLon = getIntent().getDoubleExtra(IntentKey.Location.KEY_START_LONGITUDE, 0);
        mEndLat = getIntent().getDoubleExtra(IntentKey.Location.KEY_END_LATITUDE, 0);
        mEndLon = getIntent().getDoubleExtra(IntentKey.Location.KEY_END_LONGITUDE, 0);
        mEndAddress = getIntent().getStringExtra(IntentKey.Location.KEY_OIL_ADDRESS);
        mOilName = getIntent().getStringExtra(IntentKey.Location.KEY_OIL_NAME);
        mTxtNaviOilName.setText(mOilName);
        mTxtNaviOilAddress.setText(mEndAddress);
    }

    @Override
    public void initData() {
        initMap();
    }

    /**
     * 控件初始化
     */
    private void init() {
        // 地图初始化
        mMapView = (MapView) findViewById(R.id.id_baidu_map);
        mTxtNaviOilName = (TextView) findViewById(R.id.id_navi_oil_name_txt);
        mTxtNaviOilAddress = (TextView) findViewById(R.id.id_navi_oil_address_txt);
        findViewById(R.id.id_navi_rela).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //导航
                showMapDialog();
//                startNavi();
            }
        });
    }

    /**
     * 弹出地图选择框
     */
    public void showMapDialog() {
        View mView = getLayoutInflater().inflate(R.layout.aty_choosse_map, null);
        final Dialog mDialog = DialogUtils.selfDialog(aty, mView, true);
        mView.findViewById(R.id.id_gaode_map_txt).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //高德地图导航
                mDialog.dismiss();
                startAMapNavi();
//                if (!getAppIn()) {
//                    //没有安装
//                    startGDMap();
//                } else {
//                    //已安装
//
//                }
            }
        });

        mView.findViewById(R.id.id_baidu_map_txt).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //百度地图导航
                mDialog.dismiss();
                startNavi();
            }
        });
        mDialog.show();
    }

    /**
     * 调起高德地图导航功能，如果没安装高德地图，会进入异常，可以在异常中处理，调起高德地图app的下载页面
     */
    public void startAMapNavi() {
        double[] d = StringUtils.bd09_To_Gcj02(mEndLat, mEndLon);
        // 构造导航参数
        NaviPara naviPara = new NaviPara();
        // 设置终点位置
        naviPara.setTargetPoint(new com.amap.api.maps.model.LatLng(d[0], d[1]));
        // 设置导航策略，这里是避免拥堵
        naviPara.setNaviStyle(NaviPara.DRIVING_AVOID_CONGESTION);

        // 调起高德地图导航
        try {
            AMapUtils.openAMapNavi(naviPara, getApplicationContext());
        } catch (com.amap.api.maps.AMapException e) {

            // 如果没安装会进入异常，调起下载页面
            AMapUtils.getLatestAMapApp(getApplicationContext());

        }
    }

    public void startGDMap() {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.addCategory(Intent.CATEGORY_DEFAULT);

        //将功能Scheme以URI的方式传入data
        String str = "androidamap://navi?sourceApplication=appname&amp;poiname=" + mEndAddress + "&amp;" + "lat=" + mEndLat + "&amp;lon=" + mEndLon + "&amp;dev=1&amp;style=2";
        Uri uri = Uri.parse(str);
        intent.setData(uri);

        //启动该页面即可
        startActivity(intent);
    }

    /**
     * 判断高德地图app是否已经安装
     */
    public boolean getAppIn() {
        PackageInfo packageInfo = null;
        try {
            packageInfo = this.getPackageManager().getPackageInfo(
                    "com.autonavi.minimap", 0);
        } catch (PackageManager.NameNotFoundException e) {
            packageInfo = null;
            e.printStackTrace();
        }
        // 本手机没有安装高德地图app
        if (packageInfo != null) {
            return true;
        }
        // 本手机成功安装有高德地图app
        else {
            return false;
        }
    }


    /**
     * 启动百度地图导航(Native)
     */
    public void startNavi() {
        LatLng ptStart = new LatLng(mCurrentLat, mCurrentLon);
        LatLng ptEnd = new LatLng(mEndLat, mEndLon);

        // 构建 导航参数
        NaviParaOption para = new NaviParaOption().startPoint(ptStart).endPoint(ptEnd);
        try {
            BaiduMapNavigation.openBaiduMapNavi(para, this);
        } catch (BaiduMapAppNotSupportNaviException e) {
            e.printStackTrace();
            showDialog();
        }
    }

    /**
     * 提示未安装百度地图app或app版本过低
     */
    public void showDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("您尚未安装百度地图app或app版本过低，点击确认安装？");
        builder.setTitle("提示");
        builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                OpenClientUtil.getLatestBaiduMapApp(aty);
            }
        });

        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.create().show();
    }

    /**
     * 初始化地图
     */
    private void initMap() {
        mBaiduMap = mMapView.getMap();
        // 开启定位图层
        mBaiduMap.setMyLocationEnabled(true);
        // 开启地图加载成功监听
        mBaiduMap.setOnMapLoadedCallback(this);
    }

    /**
     * 地图加载成功回掉
     */
    @Override
    public void onMapLoaded() {
        initRoute();
        //路线规划
        RoutePlan();
    }

    /**
     * 初始化路线规划
     */
    private void initRoute() {
        // 初始化搜索模块，注册事件监听
        mRouteSearch = RoutePlanSearch.newInstance();
        mRouteSearch.setOnGetRoutePlanResultListener(this);
    }

    /**
     * 路线规划
     */
    private void RoutePlan() {
        // 设置起终点信息，对于tranist search 来说，城市名无意义
        PlanNode stNode = PlanNode.withLocation(new LatLng(mCurrentLat, mCurrentLon));
        PlanNode enNode = PlanNode.withLocation(new LatLng(mEndLat, mEndLon));
        mRouteSearch.drivingSearch((new DrivingRoutePlanOption()).from(stNode).to(enNode));
    }


    @Override
    public void onGetWalkingRouteResult(WalkingRouteResult walkingRouteResult) {
    }

    @Override
    public void onGetTransitRouteResult(TransitRouteResult transitRouteResult) {
    }

    @Override
    public void onGetMassTransitRouteResult(MassTransitRouteResult massTransitRouteResult) {
    }

    @Override
    public void onGetIndoorRouteResult(IndoorRouteResult indoorRouteResult) {
    }

    @Override
    public void onGetBikingRouteResult(BikingRouteResult bikingRouteResult) {
    }

    @Override
    public void onGetDrivingRouteResult(DrivingRouteResult result) {
        if (null == result) {
            return;
        }
        if (result.error == SearchResult.ERRORNO.PERMISSION_UNFINISHED) {
            ToastUtil.showToast("授权未完成");
        } else if (result.error == SearchResult.ERRORNO.RESULT_NOT_FOUND) {
            ToastUtil.showToast("没有找到检索结果");
        } else if (result.error == SearchResult.ERRORNO.ST_EN_TOO_NEAR) {
            ToastUtil.showToast("起终点太近");
        } else if (result.error == SearchResult.ERRORNO.AMBIGUOUS_ROURE_ADDR) {
            ToastUtil.showToast("起终点或途经点地址有岐义");
        } else if (result.error == SearchResult.ERRORNO.NO_ERROR) {
            //规划成功
            int size = result.getRouteLines().size();
            if (size >= 1) {
                //有多条方案选择
                showRouteLine(result.getRouteLines().get(0));
            } else {
                ToastUtil.showToast("距离太近了");
            }
        } else {
            ToastUtil.showToast("路径规划失败");
        }
    }

    /**
     * 地图显示路径规划
     *
     * @param route
     */
    public void showRouteLine(DrivingRouteLine route) {
        DrivingRouteOverlay overlay = new MyDrivingRouteOverlay(mBaiduMap);
        mBaiduMap.setOnMarkerClickListener(overlay);
        overlay.setData(route);
        overlay.addToMap();
        overlay.zoomToSpan();
    }

    // 定制RouteOverly
    private class MyDrivingRouteOverlay extends DrivingRouteOverlay {

        public MyDrivingRouteOverlay(BaiduMap baiduMap) {
            super(baiduMap);
        }

        @Override
        public BitmapDescriptor getStartMarker() {
            return BitmapDescriptorFactory.fromResource(R.drawable.icon_st);
        }

        @Override
        public BitmapDescriptor getTerminalMarker() {
            return BitmapDescriptorFactory.fromResource(R.drawable.icon_en);
        }
    }

    @Override
    protected void onResume() {
        mMapView.onResume();
        super.onResume();
    }

    @Override
    protected void onPause() {
        mMapView.onPause();
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        if (mRouteSearch != null) {
            mRouteSearch.destroy();
        }
        BaiduMapNavigation.finish(this);
        mMapView.onDestroy();
        mMapView = null;
        super.onDestroy();
    }
}
